package com.jinke.api.modules.ums.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.ums.constant.ConfigConstant;
import com.jinke.api.modules.ums.model.SystemConfig;
import com.jinke.api.modules.ums.request.SaveConfigRequest;
import com.jinke.api.modules.ums.service.SystemConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 配置表 前端控制器
 * </p>
 *
 * @author macro
 * @since 2024-01-16
 */
@RestController
@RequestMapping("/ums/system/config")
@Api(tags = "系统配置")
@Tag(name = "系统配置", description = "系统配置")
public class SystemConfigController {

    @Resource
    SystemConfigService systemConfigService;

    @ApiOperation("所有配置项")
    @GetMapping("/list")
    @ResponseBody
    public CommonResult<List<SystemConfig>> list() {
        return CommonResult.success(systemConfigService.list());
    }

    @ApiOperation("获取最新的汇率")
    @GetMapping("/getUsdRate")
    @ResponseBody
    public CommonResult<String> getUsdRate() {
        SystemConfig systemConfig = systemConfigService.getByKey(ConfigConstant.USD_RATE);
        return CommonResult.success(systemConfig.getConfigValue());
    }

    @ApiOperation("保存配置")
    @PostMapping("/save")
    @ResponseBody
    public CommonResult<?> save(@RequestBody SaveConfigRequest request) {
        if (request.getKeyValue() == null) {
            return CommonResult.failed("错误的数据格式");
        }

        request.getKeyValue().forEach((k, v) -> {
            UpdateWrapper<SystemConfig> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("config_key", k);
            updateWrapper.set("config_value", v);
            systemConfigService.update(null, updateWrapper);
        });

        return CommonResult.success();
    }

}

